<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use Exception;
use PDOStatement;
use think\Log;
use think\Model;
use XznsTools\cache\CacheManage;

class MiniQiandao extends BaseCache
{
    private const LOG_PRE = '小程序MiniQiandao Model 异常：';

    protected $table = 'wechat_backup_07_18_14_43_00.mini_qiandao';
    protected $cacheModel = 'mini.sign';

    /**
     * @param $data
     * @return bool
     */
    public function SavaData($data): bool
    {
        try
        {
            $this->save($data);

            //插入成功删除缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['mini_uid'])->batchDelKey();
        }
        catch (Exception $e)
        {
            Log::write(self::LOG_PRE . $e->getMessage() . '失败行数：' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取用户签到信息
     * @param $uid
     * @return array
     * @throws Exception
     */
    public function getUserQiandao($uid): array
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            return $this->getSignsFromDms($uid);
        });

        return $data;
    }

    /**
     * 数据库查询用户的一周内的签到情况
     * @param $uid
     * @return array|mixed|PDOStatement|string|Model
     */
    public function getSignsFromDms($uid)
    {
        $last_week_time = strtotime(date('Y-m-d')) - 24 * 3600 * 7;
        $where = 'mini_uid=' . $uid . ' and create_time >=' . $last_week_time;
        try
        {
            $data = $this->field('create_time,num')->where($where)->order('create_time DESC')->select();
            $data = json_decode(json_encode($data, true), true);
            //数据转换
            $result = [];
            foreach ($data as $k => $v)
            {
                $result[$v['create_time']] = $v['num'];
            }
        }
        catch (Exception $e)
        {
            $result = [];
            Log::write(self::LOG_PRE . $e->getMessage() . '失败行数：' . $e->getLine(), 'error', true);
        }
        return $result;
    }
}
